package com.funny.stock.config.security;

import com.funny.stock.base.util.PropertiesCopyUtil;
import com.funny.stock.config.ErrorConstants;
import com.funny.stock.user.dao.pojo.SysPermissionDO;
import com.funny.stock.user.dao.pojo.SysRoleDO;
import com.funny.stock.user.dao.pojo.SysUserDO;
import com.funny.stock.user.dao.repo.SysRoleRepo;
import com.funny.stock.user.dao.repo.SysUserRepo;
import com.funny.stock.user.util.UserSecurityUtil;
import com.funny.stock.user.vo.SysUserVO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * @author pengl
 * @date 2020/11/19
 */
@Component
public class UserAuthService implements UserDetailsService {
    @Autowired
    SysUserRepo sysUserRepository;

    @Autowired
    SysRoleRepo roleRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserDO user = sysUserRepository.findByLoginAccount(username);
        if(user == null){
            UserSecurityUtil.setRequestFailMsg(ErrorConstants.USERNAME_NOT_FOUNT);
            throw new UsernameNotFoundException(ErrorConstants.USERNAME_NOT_FOUNT);
        }

        if(user.getActive() != 1){
            UserSecurityUtil.setRequestFailMsg(ErrorConstants.USER_FORBIDDEN);
            return null;
        }

        Optional<SysRoleDO> optional = roleRepository.findById(user.getRoleId());
        if(!optional.isPresent()) {
            UserSecurityUtil.setRequestFailMsg(ErrorConstants.USERNAME_NOT_FOUNT);
            return null;
        }

        SysUserVO sysUserVO = PropertiesCopyUtil.copyProperties(user, SysUserVO.class);
        UserSecurityUtil.setUser(sysUserVO);

        Set<SysPermissionDO> rolePermissions = optional.get().getRolePermissions();
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        rolePermissions.forEach(item -> grantedAuthorities.add(new SimpleGrantedAuthority(item.getName())));
        return new org.springframework.security.core.userdetails.User(user.getLoginAccount(), user.getPassword(), grantedAuthorities);
    }


}
